import java.util.Comparator;
import java.util.TreeSet;

/**
 * ClassName TreeSetComparator
 * Description TODO
 * Author Hexiao
 * Date 2018/8/21 9:20
 * Version 1.0
 **/
//TreeSet排序的第二种方法：new TreeSet的时候给构造里传入comparator比较器（在比较器中复写compare方法)
public class TreeSetComparator {
    public static void main(String[] args){

        TreeSet<Person> treeSet=new TreeSet<Person>(new Comparator<Person>() {

            @Override
            public int compare(Person o1, Person o2) {
                if(o1==o2){
                    return 0;
                }
               int result= o1.getAge()-o2.getAge();
                if (result==0){
                    return o1.getName().compareTo(o2.getName());
                }
                return result;
            }
        });
        treeSet.add(new Person("张山1", 20));
        treeSet.add(new Person("张山2", 16));
        treeSet.add(new Person("张山3", 13));
        treeSet.add(new Person("张山4", 17));
        treeSet.add(new Person("张山5", 20));
        for (Person p:treeSet){
            System.out.println(p.getName()+" "+p.getAge());
        }
    }
}